package worker

import (
	"math/rand"
	"study-crontab/crontab/common"
	"time"

	"golang.org/x/sys/execabs"
)

type Executor struct {
}

var G_Executor *Executor

//执行一个任务
func (e *Executor) ExecutorJob(info *common.JobExecuteInfo) {
	go func() {
		//任务结果
		result := &common.JobExecuteResult{
			ExecuteInfo: info,
			Output:      make([]byte, 0),
		}

		//任务开始时间
		result.StartTime = time.Now()
		//初始化锁
		jobLock := G_jobMgr.CreateJobLock(info.Job.Name)
		//随机睡眠
		time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)

		//释放锁
		defer jobLock.Unlock()
		err := jobLock.TryLock()
		if err != nil {
			result.Err = err
			result.EndTime = time.Now()
			return
		} else {
			//上锁成功后重置启动时间
			result.StartTime = time.Now()
			//执行shell命令
			cmd := execabs.CommandContext(info.CancelCtx, "/bin/bash", "-c", info.Job.Command)

			//捕获执行输出
			output, err := cmd.CombinedOutput()

			//任务结束时间
			result.EndTime = time.Now()
			result.Output = output
			result.Err = err
		}

		//任务执行完成后,把执行的结果返回给Scheduler， Scheduler会从executingMap中删除掉执行记录
		G_scheduler.PushJobResult(result)

	}()
}

func NewExecutor() (err error) {
	G_Executor = &Executor{}
	return
}
